<template>
  <div class="position-relative">
    <label for="exampleInputEmail1" class="form-label">{{ label }}</label>
    <slot />
    <div class="invalid-feedback">{{ error }}</div>
  </div>
</template>
<script>
import bus from './bus';
import Schema from 'async-validator';
import { ref, onMounted, provide, inject, onUnmounted } from 'vue';
export default {
  name: 'MFormItem',
  props: {
    label: String,
    prop: String,
  },
  setup(props) {
    const form = inject('form');
    const error = ref('');
    provide('inputError', error);

    // 监听input验证
    const onInputValidate = () => {
      if (props.prop) {
        bus.$on('input-validate', () => inputValidate());
      }
    };

    //  事件派发 给form添加属性
    const emitFormAddField = () => {
      if (props.prop) {
        bus.$emit('form-addfield', inputValidate);
      }
    };

    const inputValidate = () => {
      // 拿到值和规则
      const value = form.model[props.prop];
      const rules = form.rules[props.prop];
      const desc = { [props.prop]: rules };
      // 创建校验规则
      const schema = new Schema(desc);
      // 校验结果返回的promise
      return schema.validate({ [props.prop]: value }, (errors) => {
        // console.log(invalidFields, 'invalidFields');
        if (errors) {
          error.value = errors[0].message;
        } else {
          //校验通过
          error.value = '';
        }
      });
    };

    onMounted(() => {
      // 监听input验证
      onInputValidate();
      //  事件派发 给form添加属性
      emitFormAddField();
    });

    onUnmounted(() => {
      bus.$off('form-addfield');
      bus.$off('input-validate', '');
    });
    return {
      error,
    };
  },
};
</script>
